import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

/**
 * 用户信息 Store
 * 
 * 此 store 管理用户相关的状态和操作，
 * 使用组合式 API 风格定义。
 * 
 * @returns {Object} 用户 store 对象
 */
export const useUserStore = defineStore('user', () => {
  // 响应式状态
  const user = ref(null);
  const isAuthenticated = ref(false);
  const permissions = ref([]);
  
  // Getter 计算属性
  const isAdmin = computed(() => permissions.value.includes('admin'));
  const canEdit = computed(() => isAdmin.value || permissions.value.includes('edit'));
  const canDelete = computed(() => isAdmin.value || permissions.value.includes('delete'));
  const fullName = computed(() => {
    if (!user.value) return 'Guest';
    return `${user.value.firstName} ${user.value.lastName}`;
  });
  
  // 操作函数
  const login = async (credentials) => {
    // 模拟登录请求
    return new Promise((resolve) => {
      setTimeout(() => {
        user.value = {
          id: 'u123',
          firstName: 'John',
          lastName: 'Doe',
          email: credentials.email
        };
        permissions.value = ['view', 'edit'];
        isAuthenticated.value = true;
        resolve(user.value);
      }, 1000);
    });
  };
  
  const logout = () => {
    user.value = null;
    isAuthenticated.value = false;
    permissions.value = [];
  };
  
  const updateProfile = (updates) => {
    if (user.value) {
      user.value = { ...user.value, ...updates };
    }
  };
  
  const addPermission = (permission) => {
    if (!permissions.value.includes(permission)) {
      permissions.value.push(permission);
    }
  };
  
  const removePermission = (permission) => {
    permissions.value = permissions.value.filter(p => p !== permission);
  };
  
  // 返回状态和操作
  return {
    user,
    isAuthenticated,
    permissions,
    isAdmin,
    canEdit,
    canDelete,
    fullName,
    login,
    logout,
    updateProfile,
    addPermission,
    removePermission
  };
});